<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="pageIndex=1,getDataList()" size="mini">
      <el-form-item>
        <el-button v-if="isAuth('project:contract:save')" type="primary" @click="addOrUpdateHandle()" icon="el-icon-plus" >添加合同</el-button>
      </el-form-item>
      <el-form-item style="margin-left: 20px;">
        <el-date-picker v-model="dataForm.startDate" type="date"  placeholder="开始日期" class="date_type" :picker-options="pickerOptionsStart"  @change="changeEnd"></el-date-picker> 至
        <el-date-picker v-model="dataForm.endDate" type="date"  placeholder="结束日期" class="date_type" :picker-options="pickerOptionsEnd"  @change="changeStart"></el-date-picker>
      </el-form-item>
      <el-form-item style="margin-left: 20px;">
        <el-input v-model="dataForm.key" placeholder="关键字搜索" clearable ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="pageIndex = 1,getDataList()" type="primary" plain icon="el-icon-search">查询</el-button>
        <el-button @click="exportExcelHandle()" type="success" icon="el-icon-printer">导出Excel</el-button>
        <el-button @click="gotoSignHandle()" type="primary" icon="el-icon-s-data"   v-if="isAuth('project:contract:sign')">合同签收统计</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="dataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle" :row-key="getRowKeys"
              :expand-row-keys="expands" @sort-change="changeSort" @current-change="toggleRowExpansion" style="width: 100%;" :header-cell-style="{background: 'steelblue',color:'white'}" >
      <el-table-column type="expand" >
        <template slot-scope="props">
          <el-table  :data="props.row.projectList" style="width: 98%;margin-left: 2%;"  border :header-cell-style="{background: 'lightblue',color:'white'}">
            <el-table-column label="项目编号" prop="projectNo" width="120"></el-table-column>
            <el-table-column label="项目名称" prop="projectName" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column label="项目启动时间" prop="projectStartDateTime" width="120" >
              <template slot-scope="scope">{{scope.row.projectStartDateTime != null? scope.row.projectStartDateTime.substring(0,10) : ''}}</template>
            </el-table-column>
            <el-table-column label="项目跟单员" prop="projectBusiness" width="120"></el-table-column>
            <el-table-column label="生产负责人" prop="projectProduce" width="120"></el-table-column>
            <el-table-column label="项目类型" prop="projectType">
              <template slot-scope="scope"> <el-tag v-for="(item,index) in scope.row.projectType.split(',')" :key="index" style="margin-left: 5px;">{{item}}</el-tag></template>
            </el-table-column>
            <el-table-column  width="150" label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="addOrUpdateProjectHandle(id = scope.row.id)" v-if="isAuth('project:project:update')">修改</el-button>
                <el-button type="danger" size="mini" @click="deleteProjectHandle(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column prop="contractNo" header-align="center" align="center" width="120" label="合同编号" sortable :sort-orders="['descending','ascending']"></el-table-column>
      <el-table-column prop="contractName" header-align="center" align="left" label="合同名称" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="contractAuthorize" header-align="center" align="center" label="委托单位" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="contractBusiness" header-align="center" align="center" width="120" label="业务负责人" sortable :sort-orders="['descending','ascending']"></el-table-column>
      <el-table-column prop="contractType" header-align="center" align="center" width="100" label="合同类型">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.contractType === 0" size="small" type="success">合同委托</el-tag>
          <el-tag v-else-if="scope.row.contractType === 1" size="small" type="warning">一般合同</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="contractMoney" header-align="center" align="right" width="120" label="合同金额">
        <template slot-scope="scope">{{scope.row.contractMoney.toFixed(2)}}</template>
      </el-table-column>
<!--      <el-table-column prop="contractAddTime" header-align="center" align="center" width="120" label="签订时间">-->
<!--        <template slot-scope="scope">{{scope.row.contractAddTime != null? scope.row.contractAddTime.substring(0,10) : ''}}</template>-->
<!--      </el-table-column>-->
      <el-table-column prop="contractCreateTime" header-align="center" align="center" width="120" label="创建时间">
        <template slot-scope="scope">{{scope.row.contractCreateTime != null? scope.row.contractCreateTime.substring(0,10) : ''}}</template>
      </el-table-column>
      <el-table-column header-align="center" align="left" width="395" label="操作" style="z-index: -1">
        <template slot-scope="scope">
          <el-button type="warning" size="mini" @click="addOrUpdateProjectHandle(id = '' ,scope.row)" v-if="isAuth('project:project:save')">添加项目</el-button>
          <el-button type="primary" size="mini" @click="addOrUpdateHandle(scope.row.id)" v-if="isAuth('project:contract:update')">修改</el-button>
          <el-button type="danger" size="mini" @click="deleteHandle(scope.row)" v-if="isAuth('project:contract:delete')">删除</el-button>

          <el-button v-if="scope.row.attachFilename" type="success" size="mini" @click="lookoverFile(scope.row.attachFilename)" style="background-color: #0000cc">附件</el-button>
          <el-button v-if="scope.row.contractFilename && isAuth('project:contract:delete')" type="success" size="mini" @click="lookoverFile(scope.row.contractFilename)"
                     style="background-color: #0000cc">合同</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[25, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改  合同-->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <!-- 弹窗, 新增 / 修改  项目-->
    <project-add-or-update v-if="projectAddOrUpdateVisible" ref="projectAddOrUpdate" @refreshDataList="getDataList" ></project-add-or-update>
  </div>
</template>

<script>
  import Vue from 'vue'
  import AddOrUpdate from './contract-add-or-update'
  import ProjectAddOrUpdate from './project-add-or-update'
  import moment from 'moment'

  export default {
    data () {
      return {
        expands: [],
        pickerOptionsStart: {},
        pickerOptionsEnd: {},
        dataForm: {
          key: '',
          sidx: 'id',
          order: 'desc',
          startDate: '',
          endDate: ''
        },
        downContractUrl: window.SITE_CONFIG['baseUrl'] + '/project/contract/download?contractNo=',  // 合同下载路径接口,
        tokenHeaders: { token: Vue.cookie.get('token') },  // token请求
        dataList: [],
        pageIndex: 1,
        pageSize: 25,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        projectAddOrUpdateVisible: false
      }
    },
    components: {
      AddOrUpdate,
      ProjectAddOrUpdate
    },
    mounted () {
      this.pageSize = 25
      this.pageIndex = 1
      this.dataForm.startDate = new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1)
      this.changeEnd()
      this.dataForm.endDate = new Date(new Date().getFullYear(), new Date().getMonth() + 1 , 0)
      this.changeStart()
      this.getDataList()
    },
    methods: {
      // 排序字段改变
      changeSort (val) {
        console.log(val)
        switch (val.order) {
          case 'ascending':
            this.dataForm.order = 'asc'
            break
          case 'descending':
            this.dataForm.order = 'desc'
            break
          default:
            this.dataForm.order = 'desc'
        }
        this.dataForm.sidx = val.prop
        this.getDataList()
      },
      // 获取数据列表
      getDataList (contractNo = '') {
        let startDate = ''
        let endDate = ''
        if (this.dataForm.startDate != null) startDate = moment(new Date(this.dataForm.startDate)).format('YYYY-MM-DD')
        if (this.dataForm.endDate != null) endDate = moment(new Date(this.dataForm.endDate)).format('YYYY-MM-DD')
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/project/contract/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'key': this.dataForm.key,
            'sidx': this.dataForm.sidx,
            'order': this.dataForm.order,
            'startDate': startDate,
            'endDate': endDate
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
            if (contractNo !== '') this.expands.push(contractNo)
          } else {
            this.dataList = []
            this.totalPage = 0
            this.$message.error(data.msg)
          }
          this.dataListLoading = false
        })
      },
      // 开始时间改变
      changeStart () {
        this.pickerOptionsStart = Object.assign({}, this.pickerOptionsStart, {
          disabledDate: (time) => {
            return time.getTime() > this.dataForm.endDate
          }
        })
        this.pageIndex = 1
        this.getDataList()
      },
      // 结束时间改变
      changeEnd () {
        this.pickerOptionsEnd = Object.assign({}, this.pickerOptionsEnd, {
          disabledDate: (time) => {
            return time.getTime() < this.dataForm.startDate
          }
        })
        this.pageIndex = 1
        this.getDataList()
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改 合同
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 新增 / 修改 项目
      addOrUpdateProjectHandle (id, item) {
        this.projectAddOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.projectAddOrUpdate.init(id, item)
        })
      },
      // 删除
      deleteHandle (scop) {
        this.$confirm('确定对合同编号[' + scop.contractNo + ']进行删除操作?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (scop.projectList.length > 0) {
            this.$confirm('该合同下有关联项目是否也进行删除操作?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.deleteContractApi(scop)
            })
          } else {
            this.deleteContractApi(scop)
          }
        })
      },
      // 删除合同接口
      deleteContractApi(scop){
        var ids = scop.id ? [scop.id] : this.dataListSelections.map(item => {
          return item.ids
        })
        this.$http({
          url: this.$http.adornUrl('/project/contract/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500
            })
            this.getDataList()
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      toggleRowExpansion (row) {
        this.expands = []
        this.expands.push(row.contractNo)
      },
      // 获取row的key值
      getRowKeys (row) {
        return row.contractNo
      },
      // 查看合同文件
      lookoverFile (filename) {
        window.open(window.SITE_CONFIG['uploadUrl'] + 'contract/' + filename )
      },
      // 导出合同列表
      exportExcelHandle () {
        this.dataListLoading = true
        let startDate = moment(this.dataForm.startDate).format('YYYY-MM-DD')
        let endDate = moment(this.dataForm.endDate).format('YYYY-MM-DD')
        this.$http({
          url: this.$http.adornUrl('/project/contract/exportExcel'),
          method: 'get',
          params: this.$http.adornParams({
            'key': this.dataForm.key,
            'sidx': this.dataForm.sidx,
            'order': this.dataForm.order,
            'startDate': startDate,
            'endDate': endDate
          }),
          responseType: 'blob'
        }).then(({data}) => {
          var downloadElement = document.createElement('a')
          var href = window.URL.createObjectURL(data) // 创建下载的链接
          downloadElement.href = href
          downloadElement.download = '合同列表（' + startDate + '至' + endDate + '）.xls' // 下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() // 点击下载
          document.body.removeChild(downloadElement) // 下载完成移除元素
          window.URL.revokeObjectURL(href) // 释放掉blob对象
          this.dataListLoading = false
        })
      },
      // 删除项目将项目放入回收站
      deleteProjectHandle (item) {
        let tip = '此操作将项目编号为[' + item.projectNo + ']的项目放入回收站, 是否继续?'
        this.$confirm(tip, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/project/project/delete'),
            method: 'post',
            data: this.$http.adornData(item.id, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500
              })
              this.getDataList()
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      // 合同签收统计
      gotoSignHandle () {
        this.$router.push({path: '/project-contractsign'})
      }
    }
  }
</script>

<style scoped>
.date_type {
  width: 140px;
}
.date_type /deep/ .el-input__inner {
  color: #3b97d7;
  font-weight: bolder;
}
</style>
